package com.study.dao;

import com.study.domain.History;
import com.study.domain.Weather;
import com.study.util.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class HistoryDao {

    private QueryRunner queryRunner = new QueryRunner();

    public void save(Weather weather, Integer userId) {
        try {
            queryRunner.update(DbUtils.getConnection(), "insert into history(userid,date,city,wendu,shidu,feng,notice) values('" + userId + "'" +
                    ",'" + weather.getDate() + "'" +
                    ",'" + weather.getCityInfo().getCity() + "'" +
                    ",'" + weather.getData().getForecast().get(0).getLow() + weather.getData().getForecast().get(0).getHigh() + "'" +
                    ",'" + weather.getData().getShidu() + "'" +
                    ",'" + weather.getData().getForecast().get(0).getFx() + weather.getData().getForecast().get(0).getFl() + "'" +
                    ",'" + weather.getData().getForecast().get(0).getNotice() + "')");
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public List<History> list(Integer userId, String date) {
        try {
            return queryRunner.query(DbUtils.getConnection(), "select * from history where userid=" + userId + " and date like '%" + date + "%'", new BeanListHandler<>(History.class));
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    public void delById(Integer id) {
        try {
            queryRunner.update(DbUtils.getConnection(), "delete from history where id = " + id);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public History selectById(Integer id) {
        try {
            return queryRunner.query(DbUtils.getConnection(), "select * from history where id=" + id, new BeanHandler<>(History.class));
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void update(History history) {
        try {
            queryRunner.update(DbUtils.getConnection(), "update history " +
                    "set date='" + history.getDate() + "'" +
                    ",city='" + history.getCity() + "'" +
                    ",wendu='" + history.getWendu() + "'" +
                    ",shidu='" + history.getShidu() + "'" +
                    ",feng='" + history.getFeng() + "'" +
                    ",notice='" + history.getNotice() + "' where id = " + history.getId());
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
